package com.cfpl.security;

import cn.hutool.core.util.StrUtil;
import com.cfpl.admin_service.VO.LoginAdmin;
import com.cfpl.admin_service.service.AdminService;
import com.cfpl.project_common.enums.CodeEnum;
import com.cfpl.project_common.exception.BusException;
import com.cfpl.project_common.pojo.Admin;
import com.cfpl.project_common.pojo.Permission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: LYP
 * @Date: 2023/10/12 - 11:25
 * @Description: com.cfpl.admin_service.security
 * @version: 1.0
 */
@Slf4j
public class AdminDetailService implements UserDetailsService {

    @Resource
    private AdminService adminService;
//    @Resource
//    private AdminMapper adminMapper;

    //重写查询用户方法
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("********进入Security***********");
        if (StrUtil.isBlank(username)){
            throw new BusException(CodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        Admin admin = adminService.loginQueryAdmin(username);
        if (admin == null){
            throw new BusException(CodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        List<Permission> permissionList = adminService.queryAllPermissionByUserName(admin.getAdminId());
        List<String> permissions = permissionList.stream().map(Permission::getPermissionUrl).collect(Collectors.toList());

        //实现了UserDetails接口，可以直接将自己的用户对象作为认证对象, security的用户对象不好使
        LoginAdmin loginAdmin;
        loginAdmin = new LoginAdmin(admin,permissions);

//         return User.withUserDetails(loginAdmin).accountLocked(true).build();
        return loginAdmin;
    }
}
